package com.shenma2009.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 军哥
 * @version 1.0
 * @description: 死信队列配置类
 * @date 2022/2/9 18:50
 */

@Configuration
public class RabbitMqConfig {
    // 订单超时队列
    @Bean
    public Queue orderTimeOutQueue() {
        return new Queue("orderTimeOutQueue");
    }

    // 死信交换机
    @Bean
    public DirectExchange orderTimeOutExchange() {
        return new DirectExchange("orderTimeOutExchange");
    }

    // 把死信队列绑定到死信交换机上
    @Bean
    public Binding bindOrderTimeOutExchange() {
        return BindingBuilder.bind(orderTimeOutQueue()).to(orderTimeOutExchange()).with("timeout");
    }

    // 订单交换机
    @Bean
    public DirectExchange orderExchange() {
        return new DirectExchange("orderExchange");
    }

    // 创建业务队列
    @Bean
    public Queue orderQueue() {
        Map<String, Object> args = new HashMap<>(2);
        //--1 过期时间1分钟
        args.put("x-message-ttl", 60*1000);

        //--2 x-dead-letter-exchange    这里声明当前队列绑定的死信交换机
        args.put("x-dead-letter-exchange", "orderTimeOutExchange");

        //--3x-dead-letter-routing-key  这里声明当前队列的死信路由key
        args.put("x-dead-letter-routing-key", "timeout");

        Queue businessQueue = QueueBuilder.durable("orderQueue").withArguments(args).build();
        return businessQueue;
    }

    // 把业务队列绑定到业务交换机上：routingkey是什么，无所谓，因为没有消费者
    @Bean
    public Binding orderBinding() {
        return BindingBuilder.bind(orderQueue()).to(orderExchange()).with("");
    }
}
